package com.shaoshaohuo.app.ui.ec;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.DumpGoodsAdapter;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.ListViewAction;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.SupplyRecord;
import com.shaoshaohuo.app.entity.SupplyRecordEntity;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.utils.DeviceHelper;
import com.shaoshaohuo.app.utils.StringHelper;
import com.shaoshaohuo.app.utils.StringUtil;
import com.shaoshaohuo.app.utils.ViewUtil;
import com.shaoshaohuo.app.utils.city.Cityinfo;
import com.shaoshaohuo.app.utils.im.IMFactory;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.XListView;
import com.shaoshaohuo.app.view.XListView.IXListViewListener;
import com.shaoshaohuo.app.view.citymenu.CascadingMenuPopWindow;
import com.shaoshaohuo.app.view.citymenu.entity.Area;
import com.shaoshaohuo.app.view.citymenu.interfaces.CascadingMenuViewOnSelectListener;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenu;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuCreator;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuItem;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuListView.OnMenuItemClickListener;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName DumpHallActivity
 * @author linmu
 * @Decription 甩货大厅
 * @2015-8-30 下午5:45:46
 */
public class DumpHallActivity extends BaseActivity implements OnClickListener, IXListViewListener {

	private TopbarView mTopbarView;

	private View mSelectAreaLayout;
	private XListView mListView;
	private TextView mAreaText;

	private DumpGoodsAdapter<SupplyRecord> mAdapter;

	private List<SupplyRecord> mDataList = new ArrayList<SupplyRecord>();
	private String bigpid = "";
	private String catid = "";
	private String pid = "";

	private String cityid = "";

	private String action = ListViewAction.NEW2;
	private String cursor = "";
	private int offset = 10;
	private String shuai = "1";

	private Cityinfo selectCity; // 选中的市
	private CascadingMenuPopWindow cascadingMenuPopWindow;
    private ImageView ivIconHand;

    @Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dump_hall);
		initView();
		setUpView();
        addShade();
		requestData(true);
	}

	private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);
		mSelectAreaLayout = this.findViewById(R.id.layout_select_area);
		mListView = (XListView) this.findViewById(R.id.listview_data_list);
		mListView.setMenuCreator(new MySwipeMenuCreator());
		mListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
				 if (AccountManager.getUserId().equals(mDataList.get(position).getUserid())) {
					 return false; 
				 }
				switch (index) {
				case 0:
					IMFactory.openChat(DumpHallActivity.this, mDataList.get(position).getUserid());
					break;
				case 1:
					DeviceHelper.callPhone(DumpHallActivity.this, mDataList.get(position).getMobile());
					break;
				}
				return false;
			}
		});
		
		mAreaText = (TextView) this.findViewById(R.id.textview_tab_left);
	}

	private void setUpView() {
		mTopbarView.setCenterText("甩货大厅");
		mTopbarView.setLeftView(true, true);

		mSelectAreaLayout.setOnClickListener(this);

		setListView();
	}
    /**
     * 添加遮罩
     */
    private void addShade() {
        if (StringUtil.isEmpty(SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.SHADE_DUMP_HALL, ""))) {
            final RelativeLayout markLayout = (RelativeLayout) findViewById(R.id.layout_mark);
            markLayout.setVisibility(View.VISIBLE);
            ivIconHand = (ImageView) findViewById(R.id.icon_hand);
            TranslateAnimation myAnimation_Translate = new TranslateAnimation(ViewUtil.dip2px(this, 220f), ViewUtil.dip2px(this, 113f), 0f, 0f);
            myAnimation_Translate.setDuration(3000);
            myAnimation_Translate.setRepeatCount(Integer.MAX_VALUE);
            ivIconHand.startAnimation(myAnimation_Translate);
            markLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    markLayout.setVisibility(View.GONE);
                    SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.SHADE_DUMP_HALL, "true");
                }
            });
        }
    }
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_select_area:
			selectCity();
			break;
		}
	}

	private void selectCity() {
//		new CascadingMenuPopWindow().showInstance(this, mAreaText, new NMCascadingMenuViewOnSelectListener());
		if (cascadingMenuPopWindow == null) {
			//向三级menu添加地区数据
			cascadingMenuPopWindow = new CascadingMenuPopWindow(this);
			cascadingMenuPopWindow
					.setMenuViewOnSelectListener(new NMCascadingMenuViewOnSelectListener());
			cascadingMenuPopWindow.showAsDropDown(mAreaText, 5, 5);
		} else if (cascadingMenuPopWindow != null
				&& cascadingMenuPopWindow.isShowing()) {
			cascadingMenuPopWindow.dismiss();
		} else {
			cascadingMenuPopWindow.showAsDropDown(mAreaText, 5, 5);
		}
/*//		Intent intent = new Intent(this, SelectProvinceActivity.class);
//		startActivityForResult(intent, 0);
		AlertDialog.Builder builder = new Builder(DumpHallActivity.this);
		// builder.setView(R.layout.activity_hello);
		View inflate = View.inflate(getBaseContext(), R.layout.sanji, null);
		cityPicker = (CityPicker) inflate.findViewById(R.id.citypicker);
		cityPicker.setOnSelectingListener(new OnSelectingListener() {
			@Override
			public void selected(boolean selected) {

			}
		});
		builder.setView(inflate);
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				selectProvince = cityPicker.getprovince();
				selectCity = cityPicker.getCity();
				mAreaText.setText(selectCity.getCity_name());
				// selectProvince = (Province)
				// Data.getSerializableExtra(ExtraName.province);
				// selectCity = (City)
				// Data.getSerializableExtra(ExtraName.city);
				refrensh();
			}
		});
		builder.show();*/
	}

	class NMCascadingMenuViewOnSelectListener implements
			CascadingMenuViewOnSelectListener {

		@Override
		public void getValue(Area city, String fullname) {
//			selectCity = CityinfoUtil.convert(city);
            if (selectCity == null) {
				mAreaText.setText(fullname);
			} else {
				mAreaText.setText(selectCity.getCity_name());
			}
			refrensh();
		}

	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			/*selectProvince = (Province) Data.getSerializableExtra(ExtraName.province);
			selectCity = (City) Data.getSerializableExtra(ExtraName.city);
			mAreaText.setText(selectCity.getCityname());
			refrensh();*/
		}
	}

	private void refrensh() {
		mDataList.clear();
		onRefresh();
	}

	private void requestData(boolean isLoading) {
		if (isLoading) {
			startLoadingDialog();
		}

		if (selectCity != null) {
			cityid = selectCity.getId();
		} else {
			cityid = null;
		}

		RequestService.getInstance().supplyPublishList(this, cursor, offset + "", action, bigpid, pid, catid, cityid, shuai,
				SupplyRecordEntity.class, new RequestListener() {

					@Override
					public void onSuccess(int requestCode, BaseEntity resultData) {
						dismissLoadingDialog();
						if (resultData.isOk()) {
							SupplyRecordEntity entity = (SupplyRecordEntity) resultData;
							List<SupplyRecord> list = entity.getData().getList();
							mDataList.addAll(list);

							if ((mDataList.size() < offset) || (action.equals(ListViewAction.HISTORY2) && list.size() < offset)) {
								// mListView.setPullLoadEnable(false);
								mListView.endLoadingMore("没有更多了");
							}
							setAdapter(mDataList);

						} else {
							showToast(resultData.getMsg());
						}
						onLoad();
					}

					@Override
					public void onFailed(int requestCode, Exception error, String msg) {
						dismissLoadingDialog();
						showToast(msg);
						onLoad();
					}
				});
	}

	protected void setAdapter(List<SupplyRecord> mDataList2) {
		if (mAdapter == null) {
			mAdapter = new DumpGoodsAdapter<SupplyRecord>(this, mDataList2, false);
			mListView.setAdapter(mAdapter);
		} else {
			mAdapter.setData(mDataList2);
		}
	}

	private void setListView() {
		mListView.setPullLoadEnable(true);
		mListView.setPullRefreshEnable(true);
		mListView.setXListViewListener(this);

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// PurchaseRecord order = (Order)
				// parent.getItemAtPosition(position);
				// Intent intent = new
				// Intent(PurchaseRecordActivity.this,OrderDetailShipperActivity.class);
				// intent.putExtra(ExtraName.orderid, order.getBusinessorderid());
				// startActivity(intent);
				SupplyRecord supply = (SupplyRecord) parent.getItemAtPosition(position);
				Intent intent = new Intent(DumpHallActivity.this, SupplyDetailActivity.class);
				intent.putExtra(ExtraName.id, supply.getId());
				startActivity(intent);
			}
		});
	}

	@Override
	public void onRefresh() {
		if (mDataList.size() > 0) {
			cursor = mDataList.get(0).getCursor();
		} else {
			cursor = "";
		}
		action = ListViewAction.NEW2;
		mListView.setPullLoadEnable(true);
		requestData(false);
	}

	@Override
	public void onLoadMore() {
		if (mDataList.size() > 0) {
			cursor = mDataList.get(mDataList.size() - 1).getCursor();
		} else {
			cursor = "";
		}
		action = ListViewAction.HISTORY2;
		requestData(false);
	}

	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
	}
	@Override
	protected void onDestroy() {
		if (cascadingMenuPopWindow != null) {
			cascadingMenuPopWindow.dismiss();
		}
		super.onDestroy();
	}
	
	class MySwipeMenuCreator implements SwipeMenuCreator{
		@Override
		public void create(SwipeMenu menu) {
			SwipeMenuItem imMenu = new SwipeMenuItem(DumpHallActivity.this);
			imMenu.setBackground(new ColorDrawable(Color.parseColor("#2eabf1")));
			imMenu.setIcon(R.drawable.icon_chat_left_ad);
			imMenu.setWidth(StringHelper.dip2px(DumpHallActivity.this, 70));
			menu.addMenuItem(imMenu);
			SwipeMenuItem callMenu = new SwipeMenuItem(DumpHallActivity.this);
			callMenu.setBackground(new ColorDrawable(Color.parseColor("#6dc114")));
			callMenu.setIcon(R.drawable.icon_tel_left_ad);
			callMenu.setWidth(StringHelper.dip2px(DumpHallActivity.this, 70));
			menu.addMenuItem(callMenu);
		}
	}
}
